package crp.core.workflow.domain.expression.candidate;

import com.qwlabs.jackson.Jackson;
import com.qwlabs.lang.S2;
import com.qwlabs.cdi.Primary;
import crp.core.shared.expression.ExpressionService;
import crp.core.workflow.domain.expression.WorkflowExpressions;
import crp.core.workflow.domain.messages.WorkflowMessages;
import crp.core.workflow.domain.models.WorkflowCandidate;
import crp.core.workflow.domain.services.WorkflowCandidateLoadContext;
import crp.core.workflow.domain.services.WorkflowTaskCandidateLoader;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Map;
import java.util.Set;

@Primary
@ApplicationScoped
public class WorkflowTaskExpressionCandidateLoader implements WorkflowTaskCandidateLoader {
    private final ExpressionService expressionService;

    @Inject
    public WorkflowTaskExpressionCandidateLoader(ExpressionService expressionService) {
        this.expressionService = expressionService;
    }

    @Override
    public Set<WorkflowCandidate> load(WorkflowCandidateLoadContext context) {
        if (S2.isBlank(context.getCandidate())) {
            return Set.of();
        }
        String topic = WorkflowExpressions.candidateTopic(context.getTopic());
        try {
            Object result = expressionService.getInstance(topic)
                    .execute(
                            context.getCandidate(),
                            Map.of(WorkflowExpressions.ENV_CONTEXT_NAME, context)
                    );
            return (Set<WorkflowCandidate>) result;
        } catch (Exception e) {
            throw WorkflowMessages.INSTANCE.invalidModelCandidate(
                    context.getModel().getId(),
                    Jackson.write(context.getNode()).orElse(null));
        }
    }
}
